#pragma once
#include<string>
#include<iostream>
#include<memory>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<strings.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<functional>
#include<unistd.h>
using namespace std;

static const string defaultIp = "0.0.0.0";
//static const string defaultIp = "127.0.0.1";
static const int gnum = 1024;

enum{USAGE_ERROR=1,SOCKET_ERR,BIND_ERR};

typedef function<void (string,uint16_t,string)> func_t;

class server
{
public:
    server(const func_t &cb,const uint16_t port,const string& ip = defaultIp)
    :_callback(cb),_port(port),_sockfd(-1),_ip(ip)
    {}

    void initServer()
    {
        //创建socket
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd ==-1)
        {
            cerr<<"socket err: "<<errno<<" : "<<strerror(errno)<<endl;
            exit(SOCKET_ERR);
        }
        cout<<"socket success: "<<_sockfd<<endl;

        //绑定port
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        //local.sin_addr.s_addr = htonl(INADDR_ANY);
        local.sin_port = htons(_port);

        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n==-1)
        {
            cerr<<"bind err: "<<errno<<" : "<<strerror(errno)<<endl;
            exit(BIND_ERR);
        }
        cout<<"bind success!"<<endl;
    }

    void start()
    {
        char buffer[gnum];
        for(;;)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            //cout<<"start"<<endl;
            ssize_t s = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            //cout<<s<<endl;
            if(s>0)
            {
                buffer[s]=0;
                string clientip = inet_ntoa(peer.sin_addr);
                uint16_t clientport = ntohs(peer.sin_port);
                string message = buffer;

                cout<<clientip<<"["<<clientport<<"]#"<<message<<endl;
                _callback(clientip,clientport,message);
            }
        }
    }

    ~server(){}

private:
    uint16_t _port;
    string _ip;
    int _sockfd;
    func_t _callback;
};